package dp.mobile.comm.worker;

import java.io.IOException;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

class Connector extends WorkerBase {
	private BluetoothDevice mDevice;
	
	public Connector(BluetoothHandler handler , BluetoothDevice device) {
		super(handler);
		mDevice = device;
		
		BluetoothSocket tmp = null;
		try {
			tmp = device.createRfcommSocketToServiceRecord(EDEN_UUID);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mSocket = tmp;
	}
	
	@Override
	public void run() {
		if (mSocket != null) {
			try {
				mSocket.connect();
				//mHandler.setConnectedDevice(mDevice);
				mHandler.connected(mSocket);
				Log.i("this" , "CONNECTED");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				//if (mEventHandler != null && !mCanceled) mEventHandler.onConnectFailed();
				if (!mCanceled) mHandler.connectFailed();
			}
		}
	}

	@Override
	public void cancel() {
		if (mSocket != null) {
			mCanceled = true;
			try {
				mSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
